from entity.database.sqlite import Role
from entity.schema.role_schema import RoleOut, RoleCreate
from exception.custom_exception import CustomErrorThrowException
import logging

async def create_role_to_core(name: str, desc: str):
    """
    创建角色到核心系统
    """
    role=await Role.create(name=name, desc=desc)
    return role

async def get_role_by_id(role_id: int):
    """
    通过id获取角色
    """

    role = await Role.get_or_none(id=role_id)

    if not role:
        logging.error("角色不存在")
        raise CustomErrorThrowException(status_code=501, message="角色不存在")
    new_role=RoleOut.from_orm(role)
    return new_role


async def update_role_by_id(role_id: int, role:RoleCreate):
    """
    更新角色到核心系统
    """
    role_info = await Role.get_or_none(id=role_id)
    if not role:
        logging.error("角色不存在")
        raise CustomErrorThrowException(status_code=501, message="角色不存在")
    role_info.name = role.name
    role_info.desc = role.desc
    await role_info.save()
    return role_info

async def delete_role_by_id(role_id: int):
    """
    删除角色
    """
    role_info = await Role.get_or_none(id=role_id)
    if not role_info:
        logging.error("角色不存在")
        raise CustomErrorThrowException(status_code=501, message="角色不存在")
    await role_info.delete()
    return None